import collections


class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def pathSum(self, root, targetSum):
        """
        :type root: TreeNode
        :type targetSum: int
        :rtype: int
        """
        if not root:
            return 0
        self.ans = 0

        def search(node, targetSum):
            left_sum = collections.deque()
            right_sum = collections.deque()
            now_sum = collections.deque()
            if node.val == targetSum:
                self.ans += 1
            now_sum.append(node.val)
            if node.left:
                left_sum = search(node.left, targetSum)
            if node.right:
                right_sum = search(node.right, targetSum)
            for item in left_sum:
                if item + node.val == targetSum:
                    self.ans += 1
                now_sum.append(item + node.val)
            for item in right_sum:
                if item + node.val == targetSum:
                    self.ans += 1
                now_sum.append(item + node.val)
            return now_sum

        search(root, targetSum)

        return self.ans

